/**
 * @author Guy Sagy
 */
package controller;

import java.sql.*;
import java.io.IOException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import model.Profile;
import model.User;
import webSiteDataStore.UserData;
import model.Message;
import utilities.ParametersValidator;
import utilities.SafeSessionAccess;

public class Register extends HttpServlet
{
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                                        throws ServletException, IOException, SQLException
    {
        ParametersValidator.ValidateProgrammerParameters(request, "mode");
        
        boolean registered = false;
        String mode = request.getParameter("mode");
        if (mode.equals("doregister"))
        {
            boolean notEnoughData       = !ParametersValidator.ValidateUserParameters(request, "firstName", "lastName",
                                                                                                "userName", "emailAddress", 
                                                                                                "password");

            boolean duplicateUserName       = false;
            String[] password               = request.getParameterValues("password");
            boolean passwordsNotIdentical   = !password[0].equals(password[1]);
            
            Message displayMessage          = new Message();
            request.setAttribute("displayMessage", displayMessage);
            ResourceBundle resources = ResourceBundle.getBundle("controller.StringResources");        
                
            if (!notEnoughData && !passwordsNotIdentical)
            {
                String firstName    = request.getParameter("firstName");
                String lastName     = request.getParameter("lastName");
                String emailAddress = request.getParameter("emailAddress");
                String userName     = request.getParameter("userName");

                Profile profile = new Profile(-1, firstName, lastName, emailAddress);
                User user = new User(userName, password[0].hashCode());
                user.setProfile(profile);

                int userId = UserData.insertUser(user);
                registered = (userId >= 0);
                if (registered)
                {
                    request.setAttribute("userName", userName);
                    Cookie emailCookie = new Cookie("userName", userName);
                    emailCookie.setPath("/");
                    emailCookie.setMaxAge(60*60*24*365);
                    response.addCookie(emailCookie);

                    displayMessage.setMessageTitle(resources.getString("TITLE_REGISTRATION_SUCCESS"));
                    displayMessage.setMessageBody(resources.getString("TEXT_REGISTRATION_SUCCESS"));
                }
                else if (userId == -2)
                {
                    duplicateUserName = true;
                }
            }

            if (!registered)
            {
                String msgText;
                
                if (notEnoughData)
                {
                    msgText = resources.getString("TEXT_DATA_MISSING");
                }
                else if (passwordsNotIdentical)
                {
                    msgText = resources.getString("TEXT_PASSWORDS_NOT_IDENTICAL");
                }
                else if (duplicateUserName)
                {
                    msgText = resources.getString("TEXT_DUPLICATE_USERNAME");
                }
                else
                {
                    msgText = resources.getString("TEXT_REGISTRATION_FAILURE");
                }
                
                displayMessage.setMessageTitle(resources.getString("TITLE_REGISTRATION_FAILURE"));
                displayMessage.setMessageBody(msgText);
                response.setStatus(HttpServletResponse.SC_ACCEPTED); // TODO: created a shared user defined error code.
            }
        }

        String nextPage = "";
        String pageTitle = "";        
        if (registered)
        {
            nextPage = "/signin.jsp?mode=signIn";
            pageTitle = "Signin";
        }
        else if (!registered)
        {
            nextPage = "/register.jsp?mode=register";
            pageTitle = "Register";
        }

        request.setAttribute("presentationMedium", "desktop");
        request.setAttribute("pageTitle", pageTitle);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextPage);
        dispatcher.forward(request, response);
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
